package com.kaka.jsonmap.core.evaluator;

import com.kaka.jsonmap.core.DictionaryManager;
import com.jayway.jsonpath.internal.Utils;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class DictionaryEvaluatorGlobal extends GlobalJsonPathEvaluator implements ExpressionEvaluator, DictionaryManagerAware {

    private static final Pattern DICT_PATTERN = Pattern.compile("^dict\\(([^,]+),\\s*(.+)\\)$");

    private static final String DICT_PREFIX = "dict(";
    private DictionaryManager dictionaryManager;

    @Override
    public boolean supports(String expression) {
        return expression.startsWith(DICT_PREFIX);
    }

    @Override
    public Object evaluate(String expression, Map<String, Object> context) {
        Matcher matcher = DICT_PATTERN.matcher(expression);
        Utils.isTrue(matcher.matches(), "Invalid dictionary mapping format, expected 'dict(dictName, path)': " + expression);
        String key = matcher.group(1).trim();
        String value = matcher.group(2).trim();
        Object keyValue = super.supports(value) ? super.evaluate(value, context) : expression;
        Object mappedValue = dictionaryManager.getMappedValue(key, keyValue != null ? keyValue.toString() : null);
        if (mappedValue == null && keyValue != null) {
            log.debug("No mapping found for key '{}' in dictionary '{}', returning null", keyValue, key);
            return null;
        }
        return mappedValue;
    }

    @Override
    public void setDictionaryManager(DictionaryManager dictionaryManager) {
        this.dictionaryManager = dictionaryManager;
    }
}